import axios from 'axios';
import {getToken} from '@/utils/auth';
import { Toast } from 'mint-ui';

// 创建axios实例
const service = axios.create({
  // baseURL: process.env.BASE_API, // api的base_url
  timeout: 1000 * 180 // 请求超时时间180秒
});

// request拦截器
service.interceptors.request.use(config => {
  // Do something before request is sent
  if (getToken()) {
    config.headers['access-token'] = getToken(); // 让每个请求携带access-token
  }
  if (config.responseType === undefined) {
    config['responseType'] = 'json';
  }
  return config;
}, error => {
  Promise.reject(error);
})

// respone拦截器
service.interceptors.response.use(
  response => {
    const res = response.data;
    if (response.status !== 200) {
      Toast({
        message: res.message,
        position: 'bottom',
        duration: 5000
      });
      return response.data;
    } else {
      return response.data;
    }
  },
  error => {
    Toast({
      message: error.message,
      position: 'bottom',
      duration: 5000
    });
    return Promise.reject(error);
  }
);

export default service;
